#include <iostream>

#include "../HttpServer/HttpServer.hpp"
#include "../common/util.hpp"
#include "../common/log.hpp"
#include "control.hpp"  

#define WWWROOT "/home/dyx/Oline_judge/HttpServer/wwwroot"

static Control* g_ctrl = nullptr;//全局控制类指针

void RecoveryAllMachines(int sig)
{
    if(g_ctrl!= nullptr){
        g_ctrl->Set_All_Machines_Online();
    }
}

int main(int argc, char *argv[])
{
    if(argc!= 2){
        std::cerr<<"Usage: "<<argv[0]<<" port"<<std::endl;
        return 1;
    }
    
    HttpServer ser(std::atoi(argv[1]),1000);
    ser.SetThreadNum(4);
    ser.SetBaseDir(WWWROOT);    
    
    Control ctrl;
    g_ctrl = &ctrl;//全局控制类指针
    signal(SIGQUIT,RecoveryAllMachines);//捕捉SIGQUIT信号，用于恢复所有机器的状态

    ser.SetGET("/all_questions",[&ctrl](const HttpRequest &req , HttpResponse *resp){
        std::string html;
        ctrl.Get_All_Questions_Html(&html);
        resp->SetContent(html,"text/html;charset=UTF-8");
    });//获取所有题目的功能路由


    ser.SetGET(R"(/question/(\d+))",[&ctrl](const HttpRequest &req , HttpResponse *resp){
        std::string numb = req._matches[1];
        std::string html;
        ctrl.Get_One_Question_Html(numb,&html);
        resp->SetContent(html,"text/html;charset=UTF-8");
    });

    ser.SetPOST(R"(/judge_question/(\d+))",[&ctrl](const HttpRequest &req , HttpResponse *resp){
        std::string numb = req._matches[1];
        std::string out_json;
        ctrl.Judge(numb,req._body,&out_json);
        resp->SetContent(out_json,"application/json;charset=UTF-8");
    });


    ser.Start();
    return 0;
}